package com.cmhk.uril

import javax.imageio.ImageIO
import java.awt.AlphaComposite
import java.awt.Color
import java.awt.Font
import java.awt.Graphics2D
import java.awt.Image
import java.awt.RenderingHints
import java.awt.image.BufferedImage

/**
 * Created by tong on 16-6-24.
 */
class Watermark {

    static void markByText(String[] logoTexts, String srcImgUrl, Integer degree, OutputStream os) {
        InputStream is = null
        try {
            Image srcImg = ImageIO.read(new URL(srcImgUrl))
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB)
            Graphics2D g = buffImg.createGraphics()
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null)
            g.setColor(Color.LIGHT_GRAY)
            g.setFont(new Font("宋体", Font.BOLD, 30))
            float alpha = 0.5f
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha))
            int width = srcImg.getWidth(null)
            int height = srcImg.getHeight(null)
            Random rand = new Random()
            for (int i = 0; i < Math.floor(width / 200); i++) {
                for (int j = 0; j < Math.floor(height / 100); j++) {
                    g.rotate(Math.toRadians(degree), 200 * i, 100 * j + 50)
                    g.drawString(logoTexts[(logoTexts.length - i + j) % logoTexts.length], 200 * i, 100 * j + 50)
                    g.rotate(Math.toRadians(-degree), 200 * i, 100 * j + 50)
                }
            }
            g.dispose()

            ImageIO.write(buffImg, "JPG", os)
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            try {
                if (null != is)
                    is.close()
            } catch (Exception e) {
                e.printStackTrace()
            }
            try {
                if (null != os)
                    os.close()
            } catch (Exception e) {
                e.printStackTrace()
            }
        }
    }


}
